﻿using System;
using System.Collections.Generic;
using System.Linq;
using CooliteExamples.Code.DAL;
using CooliteExamples.Code.DTO;
using CooliteExamples.Core.Exceptions;

namespace CooliteExamples.Web.Controllers
{
    [Serializable]
    public class BookEntryController
    {
        private int _selectedBookId;
        public int SelectedBookId
        {
            get { return _selectedBookId; }
            set
            {
                _selectedBookId = value;
                _currentBook = null;
            }
        }

        private Book _currentBook;
        public Book CurrentBook
        {
            get
            {
                if (_currentBook == null)
                {
                    _currentBook = BookList.FirstOrDefault(b => b.BookId == SelectedBookId) ?? new Book();
                }

                return _currentBook;
            }
        }

        private List<Book> _bookList;
        public List<Book> BookList
        {
            get
            {
                if (_bookList == null)
                {
                    _bookList = BookDal.GetBooks();
                }

                return _bookList;
            }
        }

        public void ResetBookList()
        {
            _bookList = null;
        }

        public List<Author> GetAvailableAuthorsForBook(int bookId)
        {
            var book = BookList.FirstOrDefault(b => b.BookId == bookId);
            var authors = AuthorDAL.GetAuthors();

            // if we dont find the book, assume all authors are fair game
            if (book == null) return authors;

            var authorIdList = book.Authors.Select(a => a.AuthorId);
            return authors.Where(a => !authorIdList.Contains(a.AuthorId)).ToList();
        }

        public void AddAuthorToCurrentBook(int authorId, string authorName)
        {
            if (authorId == 0)
                authorId = AuthorDAL.SaveAuthor(new Author() {AuthorId = authorId, AuthorName = authorName});

            Author author = new Author() {AuthorId = authorId, AuthorName = authorName};
            CurrentBook.Authors.Add(author);
        }

        public void RemoveAuthorFromCurrentBook(int authorId)
        {
            if (CurrentBook.Authors.Count > 1)
            {
                var author = CurrentBook.Authors.FirstOrDefault(a => a.AuthorId == authorId);
                CurrentBook.Authors.Remove(author);
                return;
            }

            throw new BookManagerOperationException("A Book must have at least one author");
        }
    }
}
